<template>
  <view class="forgot-page">
    <uv-navbar
      :title="pageType == 'forget' ? '忘记密码' : '重置密码'"
      placeholder
      bg-color="transparent"
      auto-back
      left-icon-color="#757575"
      title-style="color: #000000; font-size: 32rpx"
    />
    <view class="forgot-body">
      <g-stage :list="stepList" :current="current" arrow />
      <template v-if="current === 0">
        <view class="forget-form">
          <uv-form
            labelPosition="top"
            :model="forms"
            :rules="rules"
            ref="formRef"
            :label-style="{
              color: '#757575',
              fontSize: '28rpx',
            }"
          >
            <uv-form-item label="请输入手机号码" label-width="400rpx" prop="phoneNumber">
              <uv-input
                v-model="forms.phoneNumber"
                placeholder="请输入"
                maxlength="11"
                clearable
                placeholder-style="fontSize: 28rpx, color: #BDBDBD"
                :customStyle="{
                  fontSize: '28rpx',
                  height: '50rpx',
                }"
              />
            </uv-form-item>
            <uv-form-item label="请输入短信验证码" label-width="400rpx" prop="code">
              <uv-input
                v-model="forms.code"
                placeholder="请输入"
                maxlength="6"
                clearable
                placeholder-style="fontSize: 28rpx, color: #BDBDBD"
                :customStyle="{
                  fontSize: '28rpx',
                  height: '50rpx',
                }"
              >
                <template v-slot:suffix>
                  <uv-code
                    ref="uCodeRef"
                    @change="(text) => (tips = text)"
                    seconds="60"
                    change-text="X秒重新获取"
                  />
                  <uv-text @click="getCode" :text="tips" color="#4EA770" size="28rpx" />
                </template>
              </uv-input>
            </uv-form-item>
          </uv-form>
        </view>
      </template>
      <template v-if="current === 1">
        <view class="forget-form">
          <uv-form
            labelPosition="top"
            :model="forms"
            :rules="rules"
            ref="formRef"
            :label-style="{
              color: '#757575',
              fontSize: '28rpx',
            }"
          >
            <uv-form-item
              label="请设置6-20位新的登录密码"
              label-width="400rpx"
              prop="newPassword"
            >
              <uv-input
                v-model="forms.newPassword"
                placeholder="请输入"
                :type="showPassword ? 'text' : 'password'"
                maxlength="20"
                clearable
                placeholder-style="fontSize: 28rpx, color: #BDBDBD"
                :custom-style="{
                  fontSize: '28rpx',
                  height: '50rpx',
                }"
                suffix-icon="eye-fill"
                :suffix-icon-style="{
                  color: showPassword ? '#212121' : '#BDBDBD',
                }"
                @suffix="() => (showPassword = !showPassword)"
              />
            </uv-form-item>
            <uv-form-item
              label="请再次输入新的登录密码"
              label-width="400rpx"
              prop="password2"
            >
              <uv-input
                v-model="forms.password2"
                placeholder="请输入"
                :type="showPassword2 ? 'text' : 'password'"
                maxlength="20"
                clearable
                placeholder-style="fontSize: 28rpx, color: #BDBDBD"
                :custom-style="{
                  fontSize: '28rpx',
                  height: '50rpx',
                }"
                suffix-icon="eye-fill"
                :suffix-icon-style="{
                  color: showPassword2 ? '#212121' : '#BDBDBD',
                }"
                @suffix="() => (showPassword2 = !showPassword2)"
              />
            </uv-form-item>
          </uv-form>
        </view>
      </template>
    </view>
    <view class="forgot-btn">
      <uv-button
        :text="current == 1 ? '提交' : '下一步'"
        shape="circle"
        color="#fff"
        :disabled="disabled"
        :throttle-time="1000"
        :custom-style="{
          boxShadow: '0 6rpx 12rpx 2rpx rgba(0, 0, 0, 0.16)',
          height: '80rpx',
        }"
        :custom-text-style="{
          fontSize: '28rpx',
          color: '#4EA770',
        }"
        @click="handleNext"
      />
    </view>
  </view>
</template>
<script setup>
import { ref, reactive, computed } from "vue";
import { onLoad, onBackPress } from "@dcloudio/uni-app";
import { getSmsCode, getValidateCode, postUpdatePwd } from "@/request/login.js";

const formRef = ref(); // 表单ref
const forms = reactive({
  phoneNumber: "", // 登录账号
  code: "", // 短信验证码
  newPassword: "", // 密码
  password2: "", // 确认密码
});
const rules = reactive({
  phoneNumber: [
    { required: true, message: "请输入登录账号", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (!value) {
          callback(new Error("请输入手机号码"));
        } else if (!/^1[3456789]\d{9}$/.test(value)) {
          callback(new Error("请输入正确的手机号码"));
        } else {
          callback();
        }
      },
    },
  ],
  code: [{ required: true, message: "请输入短信验证码", trigger: "blur" }],
  newPassword: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, message: "密码长度不能小于6位", trigger: "blur" },
  ],
  password2: [
    { required: true, message: "请输入确认密码", trigger: "blur" },
    { min: 6, message: "密码长度不能小于6位", trigger: "blur" },
    {
      validator: (rule, value, callback) => {
        if (value != forms.newPassword) {
          callback(new Error("两次密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
}); // 表单校验规则
const showPassword = ref(false); // 密码是否显示
const showPassword2 = ref(false); // 密码是否显示
const stepList = ref([{ label: "1.验证手机号码" }, { label: "2.设置新密码" }]); // 步骤列表
const current = ref(0); // 当前步骤
const pageType = ref("forget"); // 页面类型
const uCodeRef = ref(); // 验证码组件ref
const tips = ref("获取验证码"); // 验证码文字

onLoad((e) => {
  pageType.value = e.type;
  const form = uni.getStorageSync("userInfo");
  if (form && typeof form == "object") {
    forms.phoneNumber = form.phonenumber;
  }
})

onBackPress(() => {
  if (pageType.value == 'forget') {
    uni.removeStorageSync("TOKEN");
  }
});

// 是否禁用下一步按钮
const disabled = computed(() => {
  if (current.value === 0) {
    return !forms.phoneNumber || !forms.code;
  } else {
    return !forms.newPassword || !forms.password2;
  }
});

// 下一步
const handleNext = () => {
  formRef.value
    .validate()
    .then((valid) => {
      if (valid) {
        const { phoneNumber, code, newPassword } = forms;
        if (current.value === 0) {
          getValidateCode({
            phoneNumber,
            code,
            verificationEnum: "UPDATE_PASSWORD",
          }).then((res) => {
            if (res.code == 200) {
              current.value = 1;
              if (pageType.value == 'forget') {
                uni.setStorageSync("TOKEN", res.token);
              }
            }
          });
        } else {
          postUpdatePwd({ newPassword }).then((res) => {
            if (res.code == 200) {
              uni.showToast({
                title: "重置成功",
                icon: "none",
                success: () => {
                  setTimeout(() => {
                    uni.navigateBack({
                      delta: 1,
                    });
                  }, 2000);
                },
              });
            }
          });
        }
      }
    })
    .catch(() => {});
};

// 获取验证码
const getCode = async () => {
  if (!forms.phoneNumber) {
    uni.showToast({
      title: "请输入手机号码",
      icon: "none",
    });
    return;
  }
  if (!/^1[3456789]\d{9}$/.test(forms.phoneNumber)) {
    uni.showToast({
      title: "请输入正确的手机号码",
      icon: "none",
    });
    return;
  }
  if (uCodeRef.value.canGetCode) {
    const res = await getSmsCode("UPDATE_PASSWORD", forms.phoneNumber);
    if (res?.code == 200) {
      uni.showLoading({
        title: "正在获取验证码",
      });
      setTimeout(() => {
        uni.hideLoading();
        uni.showToast({
          title: "验证码已发送",
          icon: "none",
        });
        uCodeRef.value.start();
      }, 1000);
    }
  } else {
    uni.showToast({
      title: "倒计时结束后再发送",
      icon: "none",
    });
  }
};
</script>
<style lang="scss" scoped>
.forgot-page {
  width: 100%;
  height: 100vh;
  background-image: linear-gradient(180deg, #fff 0%, #4ea770 100%);
  position: relative;
  &::after {
    content: "";
    position: absolute;
    bottom: 304rpx;
    left: calc(50% - 178rpx);
    width: 356rpx;
    height: 435rpx;
    background-image: url("@/static/login/lock.png");
    background-size: 100%;
    background-repeat: no-repeat;
  }
  .forgot-body {
    height: auto;
    background: #fff;
    box-shadow: 0 0 20rpx 2rpx rgba(78, 167, 112, 0.2);
    border-radius: 20rpx;
    margin: 8rpx 40rpx;
    overflow: hidden;
    .forget-form {
      margin: 28rpx 20rpx;
    }
  }
  .forgot-btn {
    position: absolute;
    bottom: 88rpx;
    left: 60rpx;
    right: 60rpx;
  }
}
</style>
